﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

namespace WebStudio.Mvc.Core.Extensions
{
    /// <summary>
    /// 单选列表按钮
    /// </summary>
    public static class RadioButtonListExtension
    {

        #region 单选按钮列表
        /// <summary>
        /// 单选按钮列表
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="name"></param>
        /// <param name="items"></param>
        /// <param name="htmlAttributes"></param>
        /// <returns></returns>
        public static MvcHtmlString RadioButtonList(this HtmlHelper helper, string name, IEnumerable<string> items, object htmlAttributes)
        {
            var selectList = new SelectList(items);
            return helper.RadioButtonList(name, selectList, htmlAttributes);
        }
        #endregion

        #region 单选按钮列表
        /// <summary>
        /// 单选按钮列表
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="name"></param>
        /// <param name="items"></param>
        /// <param name="htmlAttributes"></param>
        /// <returns></returns>
        public static MvcHtmlString RadioButtonList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> items, object htmlAttributes)
        {
            TagBuilder ulTag = new TagBuilder("ul");
            ulTag.AddCssClass("radio-main");
            var selected = false;
            RouteValueDictionary dictionary = (htmlAttributes == null) ? new RouteValueDictionary() : new RouteValueDictionary(htmlAttributes);
            foreach (var item in items)
            {
                var pTag = new TagBuilder("p");
                var inputTag = new TagBuilder("input");
                inputTag.MergeAttribute("id", string.Format("{0}_{1}", name, item.Value));
                inputTag.MergeAttributes<string, object>(dictionary);
                inputTag.MergeAttribute("type", "radio");
                inputTag.MergeAttribute("name", name);
                if (!selected && item.Selected)
                    inputTag.MergeAttribute("checked", "checked");
                inputTag.MergeAttribute("value", item.Value);
                var labelTag = new TagBuilder("label");
                labelTag.MergeAttribute("for", string.Format("{0}_{1}", name, item.Value));
                labelTag.InnerHtml = item.Text;
                pTag.InnerHtml = inputTag.ToString() + labelTag.ToString();

                ulTag.InnerHtml += pTag.ToString();
                selected = selected || item.Selected;
            }
            return MvcHtmlString.Create(ulTag.ToString());
        }
        #endregion
    }
}
